//
//  HJWebViewController.m
//  DaiChaoApp
//
//  Created by apple on 2019/3/7.
//  Copyright © 2019年 apple. All rights reserved.
//

#import "HJWebViewController.h"
#import <WebKit/WebKit.h>
#import "XHLaunchAd.h"
#import "dsbridge.h"
#import "HJJsApiTest.h"
#import "HJShareView.h"

@interface HJWebViewController ()<HJJsTestDelegate>
@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
//@property WebViewJavascriptBridge* bridge;
@property (nonatomic,strong) DWKWebView* dwWebView;
@end
// 桥名
static NSString * const bridge = @"lejianBridge";

@implementation HJWebViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:XHLaunchAdDetailPageWillShowNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    LKLog(@"urls=%@",self.URLString);
    if (self.isPushLogin) {
        UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [leftBtn setImage:setImage(@"back_black_left") forState:0];
        leftBtn.adjustsImageWhenHighlighted = YES;
        leftBtn.frame = CGRectMake(10, 30, leftBtn.currentImage.size.width, leftBtn.currentImage.size.height);
        @weakify(self)
        [[leftBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    }
    
    CGFloat navbarHeight = [UIApplication sharedApplication].statusBarFrame.size.height + 44;
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, navbarHeight-2, self.view.bounds.size.width, 2)];
    self.progressView.progressViewStyle = UIProgressViewStyleBar;
    self.progressView.progressTintColor = [UIColor colorWithHex:0x000000];
    [self.navigationController.view addSubview:self.progressView];
    
    CGRect rect = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-Height_NavBar);
    if (self.isBridge) {
        self.leftNavImageName = @"back_black_left";
        DWKWebView * dwebview = [[DWKWebView alloc] initWithFrame:rect];
        dwebview.backgroundColor = HJColorRGB(245);
        dwebview.scrollView.backgroundColor = HJColorRGB(245);
        
        HJJsApiTest * jstest = [[HJJsApiTest alloc] init];
        jstest.delegate = self;
        [dwebview addJavascriptObject:jstest namespace:bridge];
        [dwebview loadUrl:self.URLString];
        self.dwWebView = dwebview;
        
        __block DWKWebView * _dwebview = dwebview;
        [dwebview setJavascriptCloseWindowListener:^{
            [_dwebview callHandler:bridge arguments:@[@1,@123] completionHandler:^(id  _Nullable value) {
                NSLog(@"value%@",value);
            }];
        }];
        [dwebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        [self.view addSubview:dwebview];
        return;
    }
    
    self.webView = [[WKWebView alloc] initWithFrame:rect];
    self.webView.backgroundColor = HJColorRGB(245);
    self.webView.scrollView.backgroundColor = HJColorRGB(245);
    [self.view addSubview:self.webView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    if(!self.URLString) return;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:(self.URLString)]];
    [self.webView loadRequest:request];
    
}



-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.progressView removeFromSuperview];
}

-(void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)didClickLeftNavAction {
    if (self.dwWebView && [self.dwWebView canGoBack]) {
        [self.dwWebView goBack];
        return;
    }
    if (self.isBridge) {
        [self.dwWebView removeJavascriptObject:bridge];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat progress = [change[NSKeyValueChangeNewKey] floatValue];
        [self.progressView setProgress:progress animated:YES];
        if(progress == 1.0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.progressView setProgress:0.0 animated:NO];
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] postNotificationName:XHLaunchAdDetailPageShowFinishNotification object:nil];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.dwWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}




#pragma mark -- JS交互 更新DWWebUI  HJJsTestDelegate
-(void)shareView {
    LKLog(@"分享");
    if (!self.isBridge) return;
//    [self.dwWebView reload];
    NSString* url = [Api stringByAppendingString:ShareApi];
    @weakify(self)
    [HJHttpTool get:url params:nil success:^(HJResponeds *result) {
        @strongify(self)
        if (![(NSDictionary *)result.data isKindOfClass:[NSNull class]] || ![(NSDictionary *)result.data isEqual:[NSNull null]]) {
            HJShareView * shareView = [[HJShareView alloc]init];
            shareView.frame = self.view.bounds;
            shareView.isweb = YES;
            shareView.shareUrl = result.data[@"url"];
            shareView.descripte = result.data[@"content"];
            shareView.title = result.data[@"title"];
            [shareView showWithView:self.view aboveSubview:self.dwWebView];
        }
    } failure:^(id result) {
        [YFHud showError:result];
    }];
}

@end
